<?php

namespace app\common\library;

use fast\Http;
use think\Hook;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

/**
 * 短信验证码类
 */
class Sms
{

    /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 900;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 6;


    /**
     * 获取最后一次手机发送的数据
     *
     * @param   int    $mobile 手机号
     * @param   string $event  事件
     * @return  Sms
     */
    public static function get($mobile, $event = 'default')
    {
        $sms = \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        Hook::listen('sms_get', $sms, null, true);
        return $sms ? $sms : null;
    }


    /***
     * @param $mobile
     * @param $content
     * @return bool
     * 短息发送  阿里云
     */
    public static function sms_send($mobile,$templateCode,$content)
    {   

        AlibabaCloud::accessKeyClient('LTAI4FjGu2pcqZ8BVdyspkHb', 'kthnyFq5szQMCcblsFoqeeqBh86rYf')->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                                  ->product('Dysmsapi')
                                  // ->scheme('https') // https | http
                                  ->version('2017-05-25')
                                  ->action('SendSms')
                                  ->method('POST')
                                  ->host('dysmsapi.aliyuncs.com')
                                  ->options([
                                                'query' => [
                                                  'RegionId' => "cn-hangzhou",
                                                  'PhoneNumbers' => $mobile,
                                                  'SignName' => "易行旅行",
                                                  'TemplateCode' => $templateCode,
                                                  'TemplateParam' => $content,
                                                ],
                                            ])
                                  ->request();
            // print_r($result->toArray());
               $res = $result->toArray();
            return $res['Message'] === 'OK' ? true:false;
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }



    /***
     * @param $mobile
     * @param $content
     * @return bool
     * 短息发送
     */
    public static function sms_send2($mobile,$content)
    {
        $cpid       = 3660;
        $channelid  = 2427;
        $timestamp  = time();
        $pwd_str    = '01234567890'.'_'.$timestamp.'_topsky';
        $pass       = md5($pwd_str);
        $content    = iconv('utf-8','gbk//ignore',$content);
        $content    = urlencode($content);
        $api        = "http://admin.sms9.net/houtai/sms.php?cpid=".$cpid."&password=".$pass."&channelid=".$channelid."&tele=".$mobile."&msg=".$content."&timestamp=".$timestamp;

        $res        = Http::sendRequest($api);
        return strpos(strval($res['msg']),'success') === false ? false : true;
    }    



    /**
     * 发送验证码
     *
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码,为空时将自动生成4位数字
     * @param   string $event  事件
     * @return  boolean
     */
    public static function send($mobile, $code = null, $event = 'default')
    {
        $code = is_null($code) ? mt_rand(1000, 9999) : $code;
        $time = time();
        $ip = request()->ip();
        $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'create_time' => $time]);
        switch ($event) {
            case 'register':
                $templateCode = 'SMS_174926079';
                break;
            case 'bindmobile':
                $templateCode = 'SMS_175175228';
                break; 
            case 'resetpwd':
                $templateCode = 'SMS_174926078';
                break;          
            case 'mobilelogin':
                $templateCode = 'SMS_174926081';
                break;
            case 'apply':
                $templateCode = 'SMS_209565097';
                break;   
           case 'receive':
                $templateCode = 'SMS_174926078';
                break;                
            default:
                $templateCode = '';
                break;
        }
        //$result = Hook::listen('sms_send', $sms, null, true);
        if ($templateCode) {
            $code = ['code'=>$code];
            $content = json_encode($code);
            $result = self::sms_send($mobile,$templateCode,$content);
         
            if (!$result) {
                $sms->delete();
                return false;
            }
            return true;
        }else{
            return false; 
        }

    }

    /**
     * 发送通知
     *
     * @param   mixed  $mobile   手机号,多个以,分隔
     * @param   string $msg      消息内容
     * @param   string $template 消息模板
     * @return  boolean
     */
    public static function notice($mobile, $msg = '', $template = null)
    {
        $params = [
            'mobile'   => $mobile,
            'msg'      => $msg,
            'template' => $template
        ];
        $result = Hook::listen('sms_notice', $params, null, true);
        return $result ? true : false;
    }

    /**
     * 校验验证码
     *
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码
     * @param   string $event  事件
     * @return  boolean
     */
    public static function check($mobile, $code, $event = 'default')
    {
        $time = time() - self::$expire;
        $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        if ($sms) {
            if ($sms['create_time'] > $time && $sms['times'] <= self::$maxCheckNums) {
                $correct = $code == $sms['code'];
                if (!$correct) {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return false;
                } else {
//                        $result = Hook::listen('sms_check', $sms, null, true);
//                    return $result;
                    return true;
                }
            } else {
                // 过期则清空该手机验证码
                self::flush($mobile, $event);
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 清空指定手机号验证码
     *
     * @param   int    $mobile 手机号
     * @param   string $event  事件
     * @return  boolean
     */
    public static function flush($mobile, $event = 'default')
    {
        \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->delete();
        Hook::listen('sms_flush');
        return true;
    }
}
